package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public CaptchaVo getCaptcha() {
        //todo 创建验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        //todo 设置验证码类型    4位验证码 字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //todo 获取验证码
        String code = specCaptcha.text().toLowerCase();
        //todo 获取验证码的key 前缀+UUID
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        //todo 获取验证码的内容 base64编码
        String image = specCaptcha.toBase64();
        stringRedisTemplate.opsForValue()
                // key 验证码的key -- 有效期 秒 -- value 验证码内容 -- 有效期 单位
                .set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        return new CaptchaVo(image, key);
    }

    /**
     * 登录业务层，登录成功返回token
     *
     * @param loginVo
     * @return String token
     */
    @Override
    public String login(LoginVo loginVo) {
        //todo 1. 判断是否输入了验证码        -->     验证码 ： 防止暴力提交
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            // 验证码未输入
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        //todo 2. 校验验证码
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        // 判断验证码是否过期
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        // 判断验证码是否正确
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //todo 3. 校验用户是否存在
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(queryWrapper);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //todo 4. 校验用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //todo 5. 校验用户密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //todo 6. 创建并返回TOKEN
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }

    /**
     * 根据用户id获取登录信息
     * @param userId
     * @return
     */
    @Override
    public SystemUserInfoVo getLoginInfoByUserId(Long userId) {
        SystemUser systemUser = systemUserService.getById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
